package controller

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"shorturl/global"
	"shorturl/model"
	"shorturl/utils"
	"strings"
)

type LinkController struct {
	BaseController
}

// Index 获取链接列表
func (app LinkController) Index(c *gin.Context) {
	noId := c.Query("no_id")         // 数字ID
	hashId := c.Query("hash_id")     // 短链接ID
	custName := c.Query("cust_name") // 别名
	longUrl := c.Query("long_url")   // 原始链接
	state := c.Query("state")        // 状态

	// 创建时间 范围
	startDate := c.Query("create_time_start")
	endDate := c.Query("create_time_end")

	pageNo := c.DefaultQuery("pageNo", "1")
	pageSize := c.DefaultQuery("pageSize", "10")

	// 把params["page"]转换成int
	page := utils.StrToInt(pageNo)
	size := utils.StrToInt(pageSize)

	if page <= 0 {
		page = 1
	}

	if size <= 0 {
		size = 10
	}

	if size > 100 {
		size = 100
	}

	var link []model.Link

	var total int64

	query := global.Db.Model(&link).Debug()

	if noId != "" {
		query = query.Where("no_id = ?", noId)
	}

	if hashId != "" {
		query = query.Where("hash_id LIKE ?", "%"+hashId+"%")
	}

	if custName != "" {
		query = query.Where("cust_name LIKE ?", "%"+custName+"%")
	}

	if longUrl != "" {
		query = query.Where("long_url LIKE ?", "%"+longUrl+"%")
	}

	if state != "" {
		query = query.Where("state = ?", state)
	}

	if startDate != "" && endDate != "" {
		query = query.Where("create_at between ? and ?", startDate, endDate)
	}

	// 查询总记录数
	query.Count(&total)

	// 查询消息列表，增加分页
	query.Order("id desc").Offset((page - 1) * size).Limit(size).Find(&link)

	var result = make(map[string]interface{})

	result["total"] = total

	result["list"] = link

	app.Success(c, result)
}

// Add 添加链接
func (app LinkController) Add(c *gin.Context) {
	var link model.Link
	if err := c.ShouldBindJSON(&link); err != nil {
		logger.Error("参数错误", zap.Error(err))
		app.Error(c, "参数错误")
		return
	}

	values := []any{link.NoId, link.HashId, link.CustName}
	err := global.Db.
		Where("no_id IN (?) OR hash_id IN (?) OR cust_name IN (?)", values, values, values).
		First(&link).
		Error

	if err == nil {
		logger.Error("存在重复链接")
		app.Error(c, "存在重复链接")
		return
	}

	link.HashId = utils.GenerateInviteCode()
	link.CreateAt = model.LocalTime(utils.GetDateTime())
	link.UpdateAt = model.LocalTime(utils.GetDateTime())

	err = global.Db.Create(&link).Error

	if err != nil {
		logger.Error("添加链接失败", zap.Error(err))
		app.Error(c, "添加链接失败")
		return
	}

	app.Success(c, link)
}

// Update 更新链接
func (app LinkController) Update(c *gin.Context) {
	var link model.Link
	if err := c.ShouldBindJSON(&link); err != nil {
		logger.Error("参数错误", zap.Error(err))
		app.Error(c, "参数错误")
		return
	}

	values := []any{link.NoId, link.HashId, link.CustName}

	err := global.Db.
		Not("id = ?", link.Id).
		Where("no_id IN (?) OR hash_id IN (?) OR cust_name IN (?)", values, values, values).
		First(&model.Link{}).
		Error

	if err == nil {
		logger.Error("存在重复链接")
		app.Error(c, "存在重复链接")
		return
	}

	link.UpdateAt = model.LocalTime(utils.GetDateTime())

	err = global.Db.Save(&link).Error

	if err != nil {
		logger.Error("更新链接失败", zap.Error(err))
		app.Error(c, "更新链接失败")
		return
	}

	app.Success(c, link)
}

// Delete 删除链接
func (app LinkController) Delete(c *gin.Context) {
	id := c.Query("id")

	ids := strings.Split(id, ",")

	var link model.Link

	err := global.Db.Where("id in (?)", ids).Delete(&link).Error

	if err != nil {
		logger.Error("删除失败", zap.Error(err))
		app.Error(c, "删除失败")
		return
	}

	app.Success(c, "删除成功")
}
